package com.diyunapp.xilinapp.myorders;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.adapters.RecycleViewMyordersAdapter;
import com.diyunapp.xilinapp.bean.MyOrdersOutBean;
import com.diyunapp.xilinapp.bean.OrderGoodsInBean;
import com.diyunapp.xilinapp.bean.OrderPayOutBean;
import com.diyunapp.xilinapp.details.PayCommitActivity;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.myapi.MyOrdersClickInterface;
import com.diyunapp.xilinapp.myapi.OnRecyclerViewItemClickListener;
import com.diyunapp.xilinapp.myindent.CheckLogisticsActivity;
import com.diyunapp.xilinapp.myindent.ReceiveActivity;
import com.diyunapp.xilinapp.myindent.WaitPayDetailActivity;
import com.diyunapp.xilinapp.utils.FormatConfirm;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by NIDAYE on 2016/6/21.
 */
public class ForEvaluationOrdersFragment extends Fragment {

    @Bind(R.id.myorders_recylerView)
    RecyclerView myordersRecylerView;
    @Bind(R.id.myorders_swiperefreshlayout)
    SwipeRefreshLayout myordersSwiperefreshlayout;
    @Bind(R.id.myorders_noorders_tv)
    TextView myordersNoordersTv;

    //支付订单列表
    private List<MyOrdersOutBean> myPaySnsList;
    private RecycleViewMyordersAdapter myPaySnsAdapter;
    private LinearLayoutManager myPaySnsManager;
    private List<OrderPayOutBean> ordersList = new ArrayList<>();
    private String loginKey = "d27d6a1b8abec70888744a6b39d9c635";
    private String memberid = "2";

    private View myPaySnsFGView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        myPaySnsFGView = inflater.inflate(R.layout.myorders_list_main_layout, null);
        ButterKnife.bind(this, myPaySnsFGView);
        loginKey = MainActivity.myLogin.getLoginkey();
        initViews();
        getOrderList();
        return myPaySnsFGView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void initViews() {

        myPaySnsManager = new LinearLayoutManager(getActivity());
        myPaySnsList = new ArrayList<>();
        myPaySnsAdapter = new RecycleViewMyordersAdapter(myPaySnsList, getActivity(), new MyOrdersClickInterface() {
            @Override
            public void OnOrdersClick(View view, int operation, String info) {
                switch (view.getId()) {
                    case R.id.myorders_paysn_payatonce_tv:  //paysn 立即付款
                        Intent payInt = new Intent(getActivity(), PayCommitActivity.class);
                        payInt.putExtra("PaySn", info);
                        startActivityForResult(payInt, 1);
                        break;
                    case R.id.myorders_pay_bt:  //orderid 确认收货、立即评价等操作按钮
                        if (operation == 30)  //待收货 确认收货
                        {
                            sureToReceive(info);
                        } else if (operation == 40)  //已收货 立即评价
                        {
                            Intent evaluationInt = new Intent(getActivity(), ReceiveActivity.class);
                            evaluationInt.putExtra("OrderId", info);
                            startActivityForResult(evaluationInt, 2);
                        }
                        break;
                    case R.id.myorders_cancel_bt:  //orderid 取消订单、查看物流、删除订单
                        if (operation == 10) //待付款 取消订单
                        {
                            cancelOrder(info);
                        } else if (operation == 30) //待收货 查看物流
                        {
                            Intent wuliuInt = new Intent(getActivity(), CheckLogisticsActivity.class);
                            wuliuInt.putExtra("PaySn", info);
                            startActivityForResult(wuliuInt, 3);
                            break;
                        } else if (operation == 0 || operation == 40)  //订单已取消或已完成 删除订单
                        {
                            deleteOrder(info);
                        }
                        break;
                    default:
                        break;
                }
            }
        });

        myordersRecylerView.setLayoutManager(myPaySnsManager);
        myordersRecylerView.setAdapter(myPaySnsAdapter);

        myordersSwiperefreshlayout.setColorSchemeColors(R.color.domain_orange, R.color.green,
                R.color.blue, R.color.yellow);

        myordersSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("zhangxiaoxidebug", "myordersSwiperefreshlayout onRefresh...");
                getOrderList();
            }
        });

        myPaySnsAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int data) {
                Intent orderDetail = new Intent(getActivity(), WaitPayDetailActivity.class);
                orderDetail.putExtra("PaySn", myPaySnsList.get(data).getPay_sn());
                String OrderIdS = "";
                for(int i=0;i<myPaySnsList.get(data).getOrdersList().size();i++)
                {
                    OrderIdS += myPaySnsList.get(data).getOrdersList().get(i).getOrder_id();
                    OrderIdS += ",";
                }
                orderDetail.putExtra("orderIdString", OrderIdS);
                startActivityForResult(orderDetail,10);
            }
        });
    }


    private void getOrderList() {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_order&op=order_list";
        RequestParams params = new RequestParams();
        //全部订单的时候仅传这一个字段
        params.addBodyParameter("key", loginKey);
        params.addBodyParameter("type", "daipingjia");

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int result = parseProject(responseInfo.result);
                        myordersSwiperefreshlayout.setRefreshing(false);
                        switch (result) {
                            case 1:
                                break;
                            case 0:
                                Toast.makeText(getActivity(), "订单查询失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onStart() {
                        myordersSwiperefreshlayout.setRefreshing(true);
                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "paysn_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");
                            JSONArray jsArrayGroup = jsObjectDatas.getJSONArray("order_group_list");
                            if(jsArrayGroup.length()<=0)
                            {
                                myordersNoordersTv.setVisibility(View.VISIBLE);
                                myordersRecylerView.setVisibility(View.GONE);
                            }
                            else
                            {
                                myordersRecylerView.setVisibility(View.VISIBLE);
                                myordersNoordersTv.setVisibility(View.GONE);
                                myPaySnsList.clear();
                                for (int paysnNum = 0; paysnNum < jsArrayGroup.length(); paysnNum++) {
                                    JSONObject jsObjectList = jsArrayGroup.getJSONObject(paysnNum);
                                    JSONArray jsArrayOrder = jsObjectList.getJSONArray("order_list");

                                    String pay_sn = "";
                                    String order_state = "";
                                    String pay_amount;
                                    if (jsObjectList.has("pay_amount")) {
                                        pay_amount = jsObjectList.getString("pay_amount");
                                    } else {
                                        pay_amount = "0";
                                    }

                                    List<OrderPayOutBean> ordersList = new ArrayList<>();
                                    for (int i = 0; i < jsArrayOrder.length(); i++) {
                                        JSONObject jsObjectOrder = jsArrayOrder.getJSONObject(i);
                                        String order_id = jsObjectOrder.getString("order_id");
                                        String order_sn = jsObjectOrder.getString("order_sn");
                                        pay_sn = jsObjectOrder.getString("pay_sn");
                                        String store_id = jsObjectOrder.getString("store_id");
                                        String store_name = jsObjectOrder.getString("store_name");
                                        String add_time = jsObjectOrder.getString("add_time");
                                        String payment_code = jsObjectOrder.getString("payment_code");
                                        String payment_time = jsObjectOrder.getString("payment_time");
                                        String finnshed_time = jsObjectOrder.getString("finnshed_time");
                                        String goods_amount = jsObjectOrder.getString("goods_amount");
                                        String order_amount = jsObjectOrder.getString("order_amount");
                                        String rcb_amount = jsObjectOrder.getString("rcb_amount");
                                        String pd_amount = jsObjectOrder.getString("pd_amount");
                                        String shipping_fee = jsObjectOrder.getString("shipping_fee");
                                        String evaluation_state = jsObjectOrder.getString("evaluation_state");
                                        order_state = jsObjectOrder.getString("order_state");
                                        String xlb_amount = jsObjectOrder.getString("xlb_amount");
                                        String state_desc = jsObjectOrder.getString("state_desc");
                                        String payment_name = jsObjectOrder.getString("payment_name");
                                        String djj = jsObjectOrder.getString("djj");
                                        String if_lock=jsObjectOrder.getString("if_lock");
                                        String is_pay = jsObjectOrder.getString("is_pay");
                                        String mansong = "";
                                        if(jsObjectOrder.has("mansong"))
                                        {
                                            mansong = jsObjectOrder.getString("mansong");
                                        }

                                        float goodsMoney_total = 0;
                                        JSONArray jsArrayGoods = jsObjectOrder.getJSONArray("extend_order_goods");
                                        List<OrderGoodsInBean> thegoodsList = new ArrayList<>();
                                        for (int j = 0; j < jsArrayGoods.length(); j++) {
                                            JSONObject jsObjectGoods = jsArrayGoods.getJSONObject(j);
                                            String rec_id=jsObjectGoods.getString("rec_id");
                                            String goods_id = jsObjectGoods.getString("goods_id");
                                            String goods_name = jsObjectGoods.getString("goods_name");
                                            String goods_image_url = jsObjectGoods.getString("goods_image_url");
                                            String goods_price = jsObjectGoods.getString("goods_price");
                                            String goods_num = jsObjectGoods.getString("goods_num");
                                            goodsMoney_total += Float.parseFloat(goods_price)*Integer.parseInt(goods_num);
                                            thegoodsList.add(new OrderGoodsInBean(order_id, rec_id,goods_id, goods_name, goods_image_url, goods_price, goods_num, 0, 0));
                                        }

                                        goods_amount = String.valueOf(goodsMoney_total);
                                        float orderMoney = FormatConfirm.stringToFloat(order_amount);
                                        float xlbMoney = FormatConfirm.stringToFloat(xlb_amount);
                                        String orderneedPay = String.valueOf(orderMoney-xlbMoney);
                                        ordersList.add(new OrderPayOutBean(order_id,
                                                order_sn, pay_sn, store_id, store_name, add_time, payment_code, payment_time, finnshed_time,
                                                goods_amount, order_amount, rcb_amount, pd_amount, shipping_fee, evaluation_state, order_state,
                                                state_desc, xlb_amount, payment_name, thegoodsList, djj,if_lock, orderneedPay,true,mansong));
                                    }
                                    myPaySnsList.add(new MyOrdersOutBean(pay_sn, order_state, ordersList, pay_amount));
                                }
                                Log.i("zhangxiaoxidebug", "outList lenth = " + myPaySnsList.size());
                                myPaySnsAdapter.notifyDataSetChanged();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        myordersSwiperefreshlayout.setRefreshing(false);
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getActivity(), "订单查询失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    public void sureToReceive(String orderid) {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_order&op=order_receive&key=" + MainActivity.myLogin.getLoginkey()
                + "&order_id=" + orderid;
        Log.i("url",url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {

                                String information = resultObject.getString("datas");
                                if (information.equals("1")) {
                                    Toast.makeText(getActivity(), "恭喜您，确认收货成功！", Toast.LENGTH_LONG).show();
                                    getOrderList();
                                } else {
                                    JSONObject errorObject = new JSONObject(information);
                                    String error = errorObject.getString("error");
                                    Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
                                }
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getActivity(), "订单查询失败，请联系客服处理！", Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getActivity(), "确认收货失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                });
    }

    public void cancelOrder(String orderid) {


        String url = "http://www.xilingou.com/mobile/index.php?act=member_order&op=order_cancel&key=" + MainActivity.myLogin.getLoginkey()
                + "&order_id=" + orderid;
        Log.i("zhangxiaoxidebugurl","++++"+url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                String information = resultObject.getString("datas");
                                if (information.equals("1")) {
                                    Toast.makeText(getActivity(), "订单已取消！", Toast.LENGTH_LONG).show();
                                    getOrderList();
                                } else {
                                    JSONObject errorObject = new JSONObject(information);
                                    String error = errorObject.getString("error");
                                    Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
                                }
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getActivity(), "订单取消失败，请联系客服处理！", Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getActivity(), "订单取消失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                });
    }

    public void deleteOrder(String orderid) {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=del_order&member_id=" + MainActivity.myLogin.getMemberid()
                + "&order_id=" + orderid;
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                String information = resultObject.getString("datas");
                                if (information.equals("1")) {
                                    Toast.makeText(getActivity(), "订单已删除！", Toast.LENGTH_LONG).show();
                                    getOrderList();
                                } else {
                                    JSONObject errorObject = new JSONObject(information);
                                    String error = errorObject.getString("error");
                                    Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
                                }
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getActivity(), "订单删除失败，请联系客服处理！", Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getActivity(), "订单删除失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getOrderList();
    }
}
